import { Component, NgZone, OnInit } from '@angular/core';
import { DomService } from '@farris/designer-services';
import { ViewModelListBuilder } from '../../../vm-designer/method-manager/services/vm-list-builder';

@Component({
    selector: 'class-editor',
    templateUrl: './class-editor.component.html',
    styleUrls: ['./class-editor.component.css'],
    providers: []
})
export class ClassEditorComponent implements OnInit {

    /** 代码编辑器实例 */
    monacoEditor;

    /** 代码编辑器配置 */
    classEditorOptions = {
        theme: 'vs-dark',
        language: 'css',
        formatOnType: true,
        foldingStrategy: 'indentation',      // 显示缩进
        folding: true,                       // 启用代码折叠功能
        showFoldingControls: 'always',       // 默认显示装订线
        automaticLayout: true
    };

    /** 代码编辑器绑定值，组件样式 */
    classCode = '';

    /** 组件列表 */
    cmpList: any[];

    /** 当前选中组件id */
    activeCmpId: string;

    constructor(
        private domService: DomService,
        private ngZone: NgZone) { }

    ngOnInit() {
        const vmBuilder = new ViewModelListBuilder(this.domService);

        const result = vmBuilder.resolveViewModelList();
        if (!result) {
            return;
        }
        this.cmpList = result.viewModelTabs || [];

        // 选中根组件
        this.activeCmpId = this.cmpList[0].componentId;
        this.onChangeSelectedCmp(this.activeCmpId);
    }

    /**
     * 切换组件
     */
    onChangeSelectedCmp(componentId: string) {
        // 自动补充的属性，不记录变更
        window.suspendChangesOnForm = true;

        // 先保存上一次的编辑数据
        if (componentId !== this.activeCmpId) {
            this.saveCustomClassToComponent(this.activeCmpId);
        }
        this.activeCmpId = componentId;

        // 获取新组件的自定义样式
        this.classCode = '';
        if (componentId) {

            if (!this.domService.module.customClass) {
                this.domService.module.customClass = {};
            }
            if (!this.domService.module.customClass[componentId]) {
                this.domService.module.customClass[componentId] = '';
            }
            this.classCode = this.domService.module.customClass[componentId];
        }
        this.formatMonacoCode();

    }

    /**
     * 保存自定义样式
     */
    private saveCustomClassToComponent(componentId: string) {
        const customClass = this.domService.module.customClass;
        if (customClass && customClass[componentId] !== this.classCode) {
            customClass[componentId] = this.classCode;
        }
    }

    public saveClassEditor() {
        const componentId = this.activeCmpId;
        if (componentId) {
            const customClass = this.domService.module.customClass;
            if (customClass[componentId] !== this.classCode) {
                customClass[componentId] = this.classCode;
            }
        }

    }

    /**
     * 格式化
     */
    private formatMonacoCode() {
        this.ngZone.runOutsideAngular(() => {
            // 挂起变更
            window.suspendChangesOnForm = true;

            setTimeout(() => {
                const action = this.monacoEditor && this.monacoEditor.getAction('editor.action.formatDocument');
                if (action) {
                    action.run().then(() => {
                        window.suspendChangesOnForm = false;
                    });
                } else {
                    window.suspendChangesOnForm = false;
                }
            }, 200);
        });
    }

    /**
     *  format editor’s content after initialized
     */
    onMonacoInit($event) {
        this.monacoEditor = $event.editor;

        // 监听代码编辑器的文本变化
        // this.monacoEditor.onDidChangeModelContent(() => {
        //     if (!window.suspendChangesOnForm && !window.isFormMetadataChanged) {

        //         // 通知IDE显示变更图标
        //         if (gsp.ide && gsp.ide.setDesignerStatus) {
        //             const iFrameTabId = gsp.ide.getParam('id');
        //             gsp.ide.setDesignerStatus(iFrameTabId, true);
        //         }

        //         // console.log('domChanged by editor');
        //         window.isFormMetadataChanged = true;
        //     }
        // });
    }
}
